package com.dlc.felear.xiaoensale.server;

import static android.os.Looper.loop;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.deviceUtil.Serialhelper;
import com.dlc.felear.xiaoensale.dlc_serial_port.DlcSerialPortClient;
import com.dlc.felear.xiaoensale.factory.CmdList;
import com.dlc.felear.xiaoensale.helper.BlueToochHelper;
import com.dlc.felear.xiaoensale.helper.JsonHelper;
import com.dlc.felear.xiaoensale.helper.Session;
import com.dlc.felear.xiaoensale.utils.HexUtil;
import com.dlc.felear.xiaoensale.utils.LogToFile;
import com.dlc.felear.xiaoensale.utils.TimeUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 后台处理逻辑
 */
public class DownloadService extends Service {

    private static final String TAG = "DownloadService";
    private ScheduledExecutorService scheduledThreadPool;
    private Session session;
    private BlueToochHelper blueToochHelper;
    private byte[] tempByte;
    private long tempStamp = 0;
    private final static String CHMD="+++";
    private final static String AT_SCAN="AT+SCAN?\n";
    private final static String AT_SCAN_CMD="AT+SCAN=1,10,1\n";

    public DownloadService() {

    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        scheduledThreadPool = new ScheduledThreadPoolExecutor(3);
        session = Session.getSession();
        blueToochHelper = BlueToochHelper.getInstance(this);
        initSerialPosrt();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(receiver, filter);
        Log.e(TAG, "onCreate");
        startService(new Intent(this, UsbService.class));
//        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
//            @Override
//            public void run() {
//                looper();
//            }
//        },1,10,TimeUnit.SECONDS);
    }

    private void looper() {
        byte[] data = CmdList.bluetoothResult(blueToochHelper.deviceType);
        receiverInputIo(data);
    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                log("BroadcastReceiver:" + device.getName());
                blueToochHelper.onDeviceFounded(device);
            }
        }
    };


    private void initSerialPosrt() {
        try {
            Serialhelper serialhelper = Serialhelper.getInstance();
            DlcSerialPortClient.getInstance().addPort(serialhelper.getKzbSerialNo(), 115200,
                    Constant.EVENT_RECEIVE_INPU_IO, 70);
            DlcSerialPortClient.getInstance().addPort(serialhelper.getDkqSerialNo(), 9600,
                    Constant.EVENT_RECEIVE_STEP_MOTOR, 500);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    /**
     * 伺服控制器串口数据
     *
     * @param orders
     */
    @Subscriber(tag = Constant.EVENT_RECEIVE_STEP_MOTOR)
    public void receiverCmd(final byte[] orders) {
        Log.e(TAG, "recieve IR data :" + HexUtil.bytes2HexString(orders));
        if (tempByte != null && tempByte.length > 0) {
            DlcSerialPortClient.getInstance().send(Serialhelper.getInstance().getKzbSerialNo(), tempByte);
        }
    }


    @Subscriber(tag = Constant.EVENT_RECEIVE_INPU_IO)
    public void receiverInputIo(final byte[] orders) {
        if (CmdList.checkDataComplete(orders) && orders[0] == (byte) 0xA5) {
//            Log.e(TAG, "EVENT_RECEIVE_INPU_IO:" + HexUtil.bytes2HexString(orders));
            EventBus.getDefault().post(HexUtil.bytes2HexString(orders), Constant.SERIALMSG);
            if (orders[1] == (byte) 0x10) {
                //握手逻辑
                blueToochHelper.sendHandsha();
                saveLog("接收握手指令:" + HexUtil.bytes2HexString(orders));
            } else if (orders[1] == (byte) 0x11) {
                //红外逻辑
                IrData(orders);
                saveLog("接收红外指令:" + HexUtil.bytes2HexString(orders));
            } else if (orders[1] == (byte) 0x12) {
                //蓝牙逻辑
                handleLyQuery(orders);
            } else if (orders[1] == (byte) 0x13) {
                blueToochHelper.clearData();
                DlcSerialPortClient.getInstance().send(Serialhelper.getInstance().getKzbSerialNo(), orders);
                saveLog("接收13指令:");
                saveLog("***********start**************");
            }
        } else {
//            Log.e(TAG, "数据验证失败 EVENT_RECEIVE_INPU_IO:" + HexUtil.bytes2HexString(orders));
        }
    }

    private void handleLyQuery(byte[] orders) {
        if (System.currentTimeMillis() - tempStamp < 30) {
            xianshiMsg("短时间内多次接收查询蓝牙指令:" + (System.currentTimeMillis() - tempStamp));
            return;
        }
//        Log.e(TAG, "time:" + (System.currentTimeMillis() - tempStamp));
        tempStamp = System.currentTimeMillis();
        DlcSerialPortClient.getInstance().send(Serialhelper.getInstance().getKzbSerialNo(), orders);
        EventBus.getDefault().post(HexUtil.bytes2HexString(orders), "LYZL");
        if (orders[2] > 0x02) {
            blueToochHelper.searchBlueDevice(HexUtil.byteToAscii(orders, 3, orders.length - 2));
        } else {
            byte[] data = CmdList.bluetoothResult("AOSMITH_17");
            blueToochHelper.searchBlueDevice(HexUtil.byteToAscii(data, 3, data.length - 2));
        }
        saveLog("接收蓝牙指令:" + HexUtil.bytes2HexString(orders));
    }

    /**
     * 红外模块转发
     *
     * @param data
     */
    private void IrData(byte[] data) {
        try {
            Log.e(TAG, "recieve IrData111:" + HexUtil.bytes2HexString(data));
            tempByte = data;
            EventBus.getDefault().post("", "HWZL");
            EventBus.getDefault().post("", "LYZL");
            blueToochHelper.clearBluData();
            byte[] dddd = CmdList.sendIrData((byte) 0xF1, data[3], data[4], data[5]);
            //发送到红外模块
            DlcSerialPortClient.getInstance().send(Serialhelper.getInstance().getDkqSerialNo(), dddd);
            DlcSerialPortClient.getInstance().send(Serialhelper.getInstance().getDkqSerialNo(), dddd);
            DlcSerialPortClient.getInstance().send(Serialhelper.getInstance().getDkqSerialNo(), dddd);
            Log.e(TAG, "send IrData111:" + HexUtil.bytes2HexString(dddd));
            EventBus.getDefault().post(HexUtil.bytes2HexString(data), "HWZL");
            xianshiMsg("发送红外检测");
        } catch (Exception e) {
            log(e.getMessage());
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unregisterReceiver(receiver);
    }

    private String zw="\\r\n";
    private String tempName="";
    @Subscriber(tag = Constant.EVENTBUS_TAG_R_LY)
    public void recieveLy(String msg) {
        Log.e(TAG, "recieveLy:" + msg);
        if(TextUtils.equals(msg,"ERROR")||TextUtils.equals(msg,"OK")){
//            xianshiMsg(msg);
            return;
        }
        handleBlueMsg(msg);
    }

    private void handleBlueMsg(String msg){
        try {
//            0 C0:09:0A:14:42:38 -50 Mi Smart Band 5
            log("handleBlueMsg:"+msg);
            String[] datas = msg.replace(zw,"").split(" ");
            Log.e(TAG, "datas:" + JsonHelper.toJson(datas));
            if (datas != null && datas.length == 4) {
                blueToochHelper.onDeviceFounded(datas[3], datas[1], datas[2]);
            }else if (datas != null && datas.length > 4&&msg.length()>23) {
                String name=msg.substring(24).replace(" ","_");
                Log.e(TAG,"name:"+name);
                blueToochHelper.onDeviceFounded(name, datas[1], datas[2]);
            }
        } catch (Exception e) {

        }
    }


    private void showMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }


    @Subscriber(tag = Constant.DEVICE_STATUS_MSG_SHOW)
    public void warnmingMsg(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }
    }

    @Subscriber(tag = Constant.SOUSUO_LY)
    public void sousuoLy(String msg) {
        Log.e(TAG, msg);
        if (TextUtils.equals(msg, "start")) {
            blueToochHelper.clearBluData();
            byte[] data = CmdList.bluetoothResult(session.getString(Constant.GZDKSJ, "AOSMITH_1746"));
            receiverInputIo(data);
        } else {
            EventBus.getDefault().post(BlueToochHelper.AT_SCAN_CANCEL.getBytes(StandardCharsets.UTF_8), Constant.EVENT_RECEIVE_INPU_IO11);
            blueToochHelper.stopScan();
        }
    }


    private void saveLog(String msg) {
//        LogToFile.getInstance().input2File(msg+"   "+ TimeUtils.getCurrrentTimeYMDHMS());
    }

    private void log(String msg) {
        Log.e(TAG, msg);
    }

    private void xianshiMsg(String msg) {
        EventBus.getDefault().post(msg, Constant.SERIALMSG);
    }

}
